﻿#region Copyright
// Copyright (c) 2011-2012 RaisingForce Team (Alikin Sergey)
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using RaisingForce.Raise.Language.Rules;

namespace RaisingForce.Raise.Language.Model
{
    sealed public class GlyphPool :
        IGlyphPool,
        IEnumerable<IGlyphContainer>
    {
        #region Constructors

        public GlyphPool(bool registerDefaultContainers = false)
        {
            if (registerDefaultContainers)
            {
                this.RegisterDefaultContainers();
            }
        }

        #endregion

        #region Private Declarations

        private readonly GlyphContainerByTypeCollection glyphContainersByType =
            new GlyphContainerByTypeCollection();

        private readonly GlyphContainerByStringCollection glyphContainersByTypeName =
            new GlyphContainerByStringCollection();

        private void addGlyphContainer(IGlyphContainer glyphContainer)
        {
            Contract.Requires(glyphContainer != null);
            this.glyphContainersByTypeName.Add(glyphContainer);
            this.glyphContainersByType.Add(glyphContainer);
        }

        private void removeGlyphContainer(IGlyphContainer glyphContainer)
        {
            Contract.Requires(glyphContainer != null);
            this.glyphContainersByType.Remove(glyphContainer);
            this.glyphContainersByTypeName.Remove(glyphContainer);
        }

        [ContractInvariantMethod]
        private void ObjectInvariant()
        {
            Contract.Invariant(this.glyphContainersByType != null);
            Contract.Invariant(this.glyphContainersByTypeName != null);
            Contract.Invariant(Contract.ForAll(this.glyphContainersByType, container => container != null));
            Contract.Invariant(Contract.ForAll(this.glyphContainersByTypeName, container => container != null));
        }

        #endregion

        #region Properties

        public int GlyphTypeCount
        {
            get
            {
                Contract.Ensures(Contract.Result<int>() >= 0);
                return this.glyphContainersByType.Count;
            }
        }

        #endregion

        #region Public Methods

        [Pure]
        public bool ContainsContainer(IGlyphContainer glyphContainer)
        {
            return this.glyphContainersByType.Contains(glyphContainer)
                || this.glyphContainersByTypeName.Contains(glyphContainer);
        }

        public void RegisterContainer(IGlyphContainer glyphContainer)
        {
            if (glyphContainer == null)
            {
                throw new ArgumentNullException("glyphContainer");
            }
            if (this.ContainsContainer(glyphContainer)
                || this.ContainsType(glyphContainer.GlyphType)
                || this.ContainsTypeName(glyphContainer.GlyphTypeName))
            {
                throw new ArgumentException("glyphContainer");
            }
            Contract.EndContractBlock();
            this.addGlyphContainer(glyphContainer);
        }

        public bool TryRegisterContainer<T>(Func<T> glyphContainerFactory)
            where T : IGlyphContainer
        {
            if (glyphContainerFactory == null)
            {
                throw new ArgumentNullException("glyphContainerFactory");
            }
            Contract.EndContractBlock();
            if (this.ContainsType(typeof(T)))
            {
                return false;
            }
            T glyphContainer = glyphContainerFactory();
            Contract.Assume(glyphContainer != null);
            if (this.ContainsContainer(glyphContainer)
                || this.ContainsTypeName(glyphContainer.GlyphTypeName))
            {
                return false;
            }
            this.addGlyphContainer(glyphContainer);
            return true;
        }

        public bool TryRegisterContainer<T>()
            where T : IGlyphContainer, new()
        {
            if (this.ContainsType(typeof(T)))
            {
                return false;
            }
            T glyphContainer = new T();
            if (this.ContainsContainer(glyphContainer)
               || this.ContainsTypeName(glyphContainer.GlyphTypeName))
            {
                return false;
            }
            this.addGlyphContainer(glyphContainer);
            return true;
        }

        public void UnregisterContainer(IGlyphContainer glyphContainer)
        {
            if (glyphContainer == null)
            {
                throw new ArgumentNullException("glyphContainer");
            }
            if (!this.ContainsContainer(glyphContainer))
            {
                throw new ArgumentException("glyphContainer");
            }
            Contract.EndContractBlock();
            this.removeGlyphContainer(glyphContainer);
        }

        public T GetGlyph<T>(string value)
            where T : Glyph
        {
            if (!this.ContainsType(typeof(T)))
            {
                throw new ArgumentException("T");
            }
            if (!GlyphRules.ValueIsValid(value)
                || !this[typeof(T)].ValueIsAllowed(value))
            {
                throw new ArgumentException("value");
            }
            Contract.Ensures(Contract.Result<T>() != null);
            Contract.EndContractBlock();
            return (T)this.glyphContainersByType[typeof(T)]
                .GetGlyph(value);
        }

        public T GetSingletonGlyph<T>()
            where T : Glyph
        {
            if (!this.ContainsType(typeof(T)))
            {
                throw new ArgumentException("T");
            }
            Contract.Ensures(Contract.Result<T>() != null);
            Contract.EndContractBlock();
            return (T)this.glyphContainersByType[typeof(T)]
                .GetSingletonGlyph();
        }

        [Pure]
        public IGlyphContainer<T> GetContainer<T>()
            where T : Glyph
        {
            if (!this.ContainsType(typeof(T)))
            {
                throw new ArgumentException("T");
            }
            Contract.Ensures(Contract.Result<IGlyphContainer<T>>() != null);
            Contract.EndContractBlock();
            return (IGlyphContainer<T>)this.glyphContainersByType[typeof(T)];
        }

        public bool RegisterDefaultContainers()
        {
            // warning: using bitwise OR, not logical OR!
            return this.TryRegisterContainer<DirectionGlyphContainer>()
                | this.TryRegisterContainer<NumberGlyphContainer>()
                | this.TryRegisterContainer<ChainGlyphContainer>()
                | this.TryRegisterContainer<ObjectGlyphContainer>()
                | this.TryRegisterContainer<ZeroGlyphContainer>()
                | this.TryRegisterContainer<CounterGlyphContainer>();
        }

        #endregion

        #region IGlyphPool Members

        public IGlyphContainer this[string glyphTypeName]
        {
            get
            {
                if (!this.ContainsTypeName(glyphTypeName))
                {
                    throw new ArgumentException("glyphTypeName");
                }
                return this.glyphContainersByTypeName[glyphTypeName];
            }
        }

        [Pure]
        public bool ContainsTypeName(string glyphTypeName)
        {
            return this.glyphContainersByTypeName
                .Contains(glyphTypeName);
        }

        public Glyph GetGlyph(string glyphTypeName, string value)
        {
            if (!GlyphRules.TypeNameIsValid(glyphTypeName)
                || !this.ContainsTypeName(glyphTypeName))
            {
                throw new ArgumentException("glyphTypeName");
            }
            if (!GlyphRules.ValueIsValid(value)
                || !this[glyphTypeName].ValueIsAllowed(value))
            {
                throw new ArgumentException("value");
            }
            return this.glyphContainersByTypeName[glyphTypeName]
                .GetGlyph(value);
        }

        public Glyph GetSingletonGlyph(string glyphTypeName)
        {
            if (!GlyphRules.TypeNameIsValid(glyphTypeName)
                || !this.ContainsTypeName(glyphTypeName))
            {
                throw new ArgumentException("glyphTypeName");
            }
            return this.glyphContainersByTypeName[glyphTypeName]
                .GetSingletonGlyph();
        }

        public IGlyphContainer this[Type glyphType]
        {
            get
            {
                if (glyphType == null)
                {
                    throw new ArgumentNullException("glyphType");
                }
                if (!this.ContainsType(glyphType))
                {
                    throw new ArgumentException("glyphType");
                }
                return this.glyphContainersByType[glyphType];
            }
        }

        [Pure]
        public bool ContainsType(Type glyphType)
        {
            return this.glyphContainersByType.Contains(glyphType);
        }

        public Glyph GetGlyph(Type glyphType, string value)
        {
            if (glyphType == null)
            {
                throw new ArgumentNullException("glyphType");
            }
            if (!this.ContainsType(glyphType))
            {
                throw new ArgumentException("glyphType");
            }
            if (!GlyphRules.ValueIsValid(value)
                || !this[glyphType].ValueIsAllowed(value))
            {
                throw new ArgumentException("value");
            }
            return this.glyphContainersByType[glyphType]
                .GetGlyph(value);
        }

        public Glyph GetSingletonGlyph(Type glyphType)
        {
            if (glyphType == null)
            {
                throw new ArgumentNullException("glyphType");
            }
            if (!this.ContainsType(glyphType))
            {
                throw new ArgumentException("glyphType");
            }
            return this.glyphContainersByType[glyphType]
                .GetSingletonGlyph();
        }

        public IList<string> GetAllowedGlyphTypeNames()
        {
            return this.glyphContainersByTypeName
                .Select(glyphContainer => glyphContainer.GlyphTypeName)
                .ToArray();
        }

        #endregion

        #region IEnumerable<IGlyphContainer> Members

        public IEnumerator<IGlyphContainer> GetEnumerator()
        {
            Contract.Ensures(Contract.Result<IEnumerator<IGlyphContainer>>() != null);
            IEnumerator<IGlyphContainer> resultingEnumerator =
                this.glyphContainersByType.GetEnumerator();
            Contract.Assume(resultingEnumerator != null);
            return resultingEnumerator;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            Contract.Ensures(Contract.Result<IEnumerator>() != null);
            return this.GetEnumerator();
        }

        #endregion
    }
}
